package processingdata.density;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

import org.geonames.InvalidParameterException;
import org.geonames.ToponymSearchCriteria;
import org.geonames.ToponymSearchResult;
import org.geonames.WebService;

public class DensityTransferData {

	public static void main(String args[]) throws Exception {
		int count = 0;
		File file = new File("project3cs424/density/density_split/density19");
		BufferedReader inputReader = new BufferedReader(new FileReader(file));
		BufferedWriter outputWriter = new BufferedWriter(new FileWriter(
				"project3cs424/density/final_split/" + file.getName()));
		HashMap<String, Double> latitudeMap = new HashMap<String, Double>();
		HashMap<String, Double> longitudeMap = new HashMap<String, Double>();

		// for (int i = 0; i < files.size(); i++) {
		// File file = new File(files.get(i));
		// BufferedReader inputReader = new BufferedReader(new FileReader(
		// new File("project3cs424/meteor_split/meteor2")));
		// BufferedWriter outputWriter = new BufferedWriter(new FileWriter(
		// new File("project3cs424/meteor_final/" + file.getName())));
		while (inputReader.ready()) {
			String inputLine = inputReader.readLine();
			if (inputLine.contains("\t")) {
				count++;

				System.out.println(inputLine + "\t" + count);
				String inputLineParts[] = inputLine.split("\t");
				String place = inputLineParts[inputLineParts.length - 2]
						+ " , " + inputLineParts[inputLineParts.length - 3];

				double latitude;
				double longitude;

				ToponymSearchCriteria searchCriteria = new ToponymSearchCriteria();
				WebService.setUserName("vivek");

				if (latitudeMap.containsKey(place)
						&& longitudeMap.containsKey(place)) {
					latitude = latitudeMap.get(place);
					longitude = longitudeMap.get(place);
				} else {
					searchCriteria.setQ(place);
					// searchCriteria.setName(city);
					searchCriteria.setCountryCode("US");

					ToponymSearchResult searchResults = WebService
							.search(searchCriteria);

					if (searchResults.getTotalResultsCount() == 0) {
						latitude = 0;
						latitudeMap.put(place, latitude);
						longitude = 0;
						longitudeMap.put(place, longitude);

					} else {

						latitude = searchResults.getToponyms().get(0)
								.getLatitude();
						latitudeMap.put(place, latitude);
						longitude = searchResults.getToponyms().get(0)
								.getLongitude();
						longitudeMap.put(place, longitude);
					}

				}

				outputWriter.write(inputLine + "\t" + latitude + "\t"
						+ longitude + "\n");
			}

		}
		outputWriter.close();

	}

}
